﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;

namespace Demo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;//使线程可以调用窗体控件
        }
        Thread th1, th2;//分别控制进度条1和进度条2
        void Pro1()
        {
            int count = 0;//标识何时加入线程2
            while (true)
            {
                progressBar1.PerformStep();//设置进度条的当前值
                count += progressBar1.Step;//标识自增
                Thread.Sleep(100);//使线程1休眠100毫秒
                if (count == 20)//标识为20时，执行线程2
                {
                    th2.Join();//使线程2调用Join()方法
                }
            }
        }
        void Pro2()
        {
            int count = 0;//标识何时执行完
            while (true)
            {
                progressBar2.PerformStep();//设置进度条的当前值
                count += progressBar2.Step;//标识自增
                Thread.Sleep(100);//使线程2休眠100毫秒
                if (count == 100)//当count变量增长为100时
                    break;//跳出循环
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            th1 = new Thread(new ThreadStart(Pro1)); //创建线程1对象
            th1.Start();//启动线程1
            th2 = new Thread(new ThreadStart(Pro2)); //创建线程2对象
            th2.Start();//启动线程2
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (th1.ThreadState == ThreadState.Running)//判断线程1是否正在运行
                th1.Abort();//终止线程1
            if (th2.ThreadState == ThreadState.Running)//判断线程2是否正在运行
                th2.Abort();//终止线程2
        }
    }
}
